package com.zx.framework.web.util;

import javax.servlet.http.HttpServletRequest;

import com.zx.framework.web.exception.AjaxException;
import com.zx.framework.web.exception.AjaxTimeoutException;
import com.zx.framework.web.exception.IframeException;
import com.zx.framework.web.exception.IframeTimeoutException;
import com.zx.framework.web.exception.PartException;
import com.zx.framework.web.exception.TimeoutException;
import com.zx.framework.web.exception.UIException;

public class RequestUtil {
	/**
	 * 判断是否ajax请求,如果参数中包含_ajax同样认为是ajax请求，用于模拟ajax请求错误
	 * 
	 * @param request
	 * @return
	 */
	public static boolean isAjax(HttpServletRequest request) {
		if (request != null
				&& "XMLHttpRequest".equalsIgnoreCase(request
						.getHeader("X-Requested-With")))
			return true;
		if("1".equals(request.getParameter("_ajax")))
			return true;
		return false;
	}
	/**
	 * 判断请求是否来自iframe
	 * @param request
	 * @return
	 */
	public static boolean isIframe(HttpServletRequest request){
		request.setAttribute("_iframe", request.getParameter("_iframe"));
		return "1".equals(request.getParameter("_iframe"));
	}
	/**
	 * 是否块加载
	 * @param request
	 * @return
	 */
	public static boolean isPart(HttpServletRequest request){
		return "1".equals(request.getParameter("_part"));
	}
	/**
	 * 获取登录接连
	 * @param request
	 * @return
	 */
	public static String getRequestUri(HttpServletRequest request){
		String url = request.getRequestURI();
		String ctx = request.getContextPath();
		int pos = url.indexOf(ctx);
		return pos==-1?"":url.substring(pos+ctx.length());
	}
	/**
	 * 根据请求类型抛出不同的异常
	 * @param request
	 * @param errorMsg 错误消息
	 * @return
	 */
	public static Exception throwException(HttpServletRequest request,String errorMsg){
		if(isAjax(request)){
			if(isPart(request)){
				throw new PartException(errorMsg);
			}
			throw new AjaxException(errorMsg);
		}else if(isIframe(request)){
			throw new IframeException(errorMsg);
		}
		else{
			throw new UIException(errorMsg);
		}
	}
	
	public static Exception throwTimeoutException(HttpServletRequest request,String errorMsg){
		if(isAjax(request)){
			if(isPart(request)){
				throw new PartException(errorMsg);
			}
			throw new AjaxTimeoutException(errorMsg);
		}else if(isIframe(request)){
			throw new IframeTimeoutException(errorMsg);
		}
		else{
			throw new TimeoutException(errorMsg);
		}
	}
}
